<?php
namespace WebApper\Shortcode;

/*
 * [mailbox]
 *
 */
 class MailBox extends \WebApper\Shortcode {
	
    /**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'mailbox';

    /**
     * Initialize the Shortcode Class
     *
     */
    public function __construct() {
		add_shortcode( $this->shortcode, array($this, 'shortcode') );
		add_action( 'wp_ajax_web_apper' . $this->shortcode, array($this, 'sendAjaxResponse') );
		add_action( 'wp_ajax_nopriv_web_apper' . $this->shortcode, array($this, 'sendAjaxResponse') );	   	
	}

    /**
     * Handles the add post shortcode
     *
     * @param array $atts
     */
	 
    public function shortcode( $atts ) {

		global $wpdb, $webapper;
		$user_ID = get_current_user_id()==0 ? 7:get_current_user_id();
		$table = $webapper->tables->emails;
		$tableAttachment = $webapper->tables->email_attachments;
		$tableLabel = $webapper->tables->email_label;
		$filePath = WEB_APPER_DIR_PATH . "email_attachments";
		$user_setting = get_user_meta($user_ID); 
		//$fromEmail = 
		$user_email = $user_setting['emailAddress'][0]; 
		$userEmailName = $user_setting['emailUserName'][0];
					
		// Check for required shortcode attributes
			$msg = $this->has_req_attrs( $atts );
			if ( $msg !== true )
				return $msg;
				
				$submit_status='';
				if(isset($_POST["sendButton"]) || isset($_POST["reply"]))
				{
					$submit_status='Sent';
				}
				else if(isset($_POST["saveButton"]))
				{
					$submit_status='Draft';
				}
				if(isset($_POST['save_lebel']))
				{
					$newLabel=$_POST['newLabel'];
					$sql = $wpdb->prepare( "INSERT INTO {$tableLabel} ( user_id, label_name ) VALUES ( %d, %s)", $user_ID, $newLabel);
					$result = $wpdb->query( $sql );					
				}
				if(isset($_POST['save_tag']))
				{	
					$tempIds = rtrim($_POST['recIds'],',');
					$tagName = $_POST['updateTag'];
					$arrayIds = explode(",",$tempIds);
					foreach ($arrayIds as $tempRec)
					{						
						$sql = $wpdb->prepare("update wp_web_apper_emails set tag = %s where user_id = %d and ID = %d",$tagName,$user_ID,$tempRec);
						$result = $wpdb->query( $sql );
					}					
				}
				
				else if(isset($_POST["sendButton"]) || isset($_POST['saveButton']) || isset($_POST["reply"]))
				{
					$to = "";
					$toEmailArray = json_decode(str_replace("\\","", $_POST["recipients_email"]));
					
					if(is_array($toEmailArray))
					{
						for($i=0; $i<count($toEmailArray); $i++)
						{
							$to.= $toEmailArray[$i].",";
						}
						$to = rtrim($to,",");
					}
					else
					{
						$to = $_POST["recipients_email"];
					}
					$subject = $_POST["subject_email"];
					$message = $_POST['content'];
					$submitTagLabel=$_POST['composeTag'];
					$submitLabel=$_POST['composeLabel']; 
					if($_FILES["filesToUpload"]["tmp_name"][0]!='')
					{
						$isAttachment="Y";
					}
					else
					{
						$isAttachment="N";
					}
					
					$current_date=date("Y-m-d H:i:s");
					$current_time=time();
					$attachments = array();
					$count = 0;
					if($submitLabel !='')
					{
						$finalLabel = $submit_status.','.$submitLabel;
					}
					else
					{
						$finalLabel = $submit_status;
					}
					//echo $table;
					$sql = $wpdb->prepare( "INSERT INTO {$table} ( user_id, `to`, to_name, `from`, from_name, subject, message_body, attachment_path, tag, label, received_on, date_on ) VALUES ( %d, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d )", $user_ID, $to, '', $user_email, $userEmailName, $subject, htmlspecialchars($message), $isAttachment, $submitTagLabel,$finalLabel, $current_date, $current_time );
										
					$result = $wpdb->query( $sql );
					if ( $result )
					{
						$lastId = $wpdb->insert_id;
						if($isAttachment == 'Y')
						{
							$files = $_FILES["filesToUpload"]["tmp_name"];
							$count=0;
							foreach($_FILES["filesToUpload"]["tmp_name"] as $file_attachment)
							{
								$attachments[$count]["string"] = file_get_contents($file_attachment);
								$attachments[$count]["type"] = $_FILES['filesToUpload']['type'][$count];
								$attachments[$count]["name"] = $_FILES['filesToUpload']['name'][$count];
								if(!is_dir($filePath . "/"))
								{
									mkdir($filePath . "/" , 0777);
									chmod($filePath . "/" , 0777);
								}
								if(!is_dir($filePath . "/" . $lastId))
								{
									mkdir($filePath . "/" . $lastId ."/", 0777);
									chmod($filePath . "/" . $lastId ."/", 0777);
								}
								$maxId = $wpdb->get_results("SELECT ifnull(MAX(ID),0)+1 AS ID FROM $tableAttachment");
								$fileType = wp_check_filetype($_FILES['filesToUpload']['name'][$count]);
								$tempFileName = $maxId[0]->ID.".".$fileType['ext'];
								$sqlAttach = $wpdb->prepare( "INSERT INTO {$tableAttachment} ( emails_id, file_path, file_name ) VALUES ( %d, %s, %s)", $lastId, $tempFileName, $_FILES['filesToUpload']['name'][$count] );
								$resultAttach = $wpdb->query( $sqlAttach );
								$path = $filePath . "/" . $lastId ."/" .$tempFileName;
								move_uploaded_file($file_attachment,$path);
								$count++;	
							}
						}						
					}
										
					if(isset($_POST["sendButton"]) || isset($_POST["reply"]))
					{
						$message = stripslashes("<html><head></head><body>".$message."</body></html>");	
						wp_mail( $to, $subject, $message, array('MIME-Version: 1.0','Content-type: text/html; charset=iso-8859-1'
						,sprintf('From: %s',$user_email),sprintf( 'X-Mailer: PHP/%s', phpversion() )), $attachments);
					
					}
				}

        // Check if current user has proper privileges
			#if ( !$this->user_has_cap( $usercap ) )
			#	return;
			?>

            <!-- DataTables Table -->
            <div class="row-fluid">            
            <div class="span2"><div class="well sidebar-nav">
            <ul class="nav nav-list">
              <li id="inbox" class="active"><a href="javascript:void(0);" onclick="javascript:changeOperationStatus('inbox','Inbox');" >Inbox</a></li>
              <li id="sent"><a href="javascript:void(0);" onclick="javascript:changeOperationStatus('sent','Sent');" >Sent</a></li>
              <li id="draft"><a href="javascript:void(0);" onclick="javascript:changeOperationStatus('draft','Draft');">Drafts</a></li>
              <li id="trash"><a href="javascript:void(0);" onclick="javascript:changeOperationStatus('trash','Trash');">Trash</a></li>
              <li id="spam"><a href="javascript:void(0);" onclick="javascript:changeOperationStatus('spam','Spam');">Spam</a></li>
              <li class="divider"></li>
              <?php				  
			  				  
					$table = $webapper->tables->email_label;
					$labels = $wpdb->get_results("SELECT * FROM $table  WHERE user_id='$user_ID' ORDER BY created_on DESC");
					$labelList = "";
					$searchLabel =array();						
					foreach ( $labels as $label )
					{
						$labelList .="<li id='lbl_".$label->ID."'><a href='javascript:void(0);' onclick=\'javascript:ChangeLabel(&#39;".$label->label_name."&#39;);\'>".$label->label_name."</a></li>";
						echo '<li id="lbl_'.$label->ID.'"><a href="javascript:void(0);" onclick="javascript:changeOperationStatus(\'lbl_'.$label->ID.'\',\''.$label->label_name.'\');">'.$label->label_name.'</a></li>';
						
						$searchLabel[]= $label->label_name;
					}
					$jsonLabel = json_encode($searchLabel);
					 //======================= START TAG LIST======================
			  		// Get the fields
					$this->get_fields( $atts );
				// Get the Custom Post Type
					$get_posts_args = array( 'post_type' => 'lead', 'order'=> 'ASC', 'orderby' => 'title', 'posts_per_page' => -1 );  // Set query arguments
					$customPostObjs = get_posts( $get_posts_args );  // Get the posts
					$customPosts = array();
					$tempFields = array();
					/*foreach ( $customPostObjs as $post ) :  // Foreach post,
						foreach ( $this->fields as $field => $fieldData ) :  // and foreach field,
							$fieldIDs .= $fieldID . ',';
							$fieldID = $fieldData['field_id'];
							$value = get_post_meta( $post->ID, $fieldID, true );  // get the field value
							if ( $this->isSerialized( $value ) ) :  // Possibly unserialize
								$value = unserialize($value);
							endif;
							if ( is_array( $value ) ) :  // Possibly cantonate array in CSV string
								$values = '';
								foreach ( $value as $val )
									$values .= $val . ', ';
								$value = substr(trim($values), 0, -1);
							endif;
							$tempFields[$fieldID] = $value;
						endforeach;
						$customPosts[$post->ID] = $tempFields;
					endforeach;*/
						/*$taglist = "";
						$searchTag = array();
						foreach ( $customPosts as $postData ) :					
							$taglist.="<li id='tag_".$postData['first-name']."'><a href='javascript:void(0);' onclick=\'javascript:ChangeTag(&#39;".$postData['first-name']."&#39;);\'>".$postData['first-name']."</a></li>";
							$searchTag[] = 	$postData['first-name'];										
						endforeach;*/
						$getRecipientEmailArray = array();
						$getAllUsers = get_users();
						$tempName = "";
						foreach($getAllUsers as $user)
						{
							$getUserMeta = get_user_meta( $user->ID);
							if($getUserMeta['first_name'][0]!='' && $getUserMeta['last_name'][0]!='')
							{
								$tempName = $getUserMeta['first_name'][0]." ".$getUserMeta['last_name'][0];
							}
							else
							{
								$tempName = $user->display_name;
							}
							if($user->user_email!='')
							{
								if($tempName =="")
								{
									$getRecipientEmailArray[] = array('id' => $user->user_email, 'name' =>$user->user_email);
								}
								else
								{
									$getRecipientEmailArray[] = array('id' => $user->user_email, 'name' =>$tempName." &lt;".$user->user_email."&gt;");
								}
							}							
						}
						$autoPopulateRecipient = json_encode($getRecipientEmailArray);
						$taglist = "";
						$searchTag = array();
						foreach($customPostObjs as $post)
						{							
							$taglist.="<li id='tag_".$post->post_title."'><a href='javascript:void(0);' onclick=\'javascript:ChangeTag(&#39;".$post->post_title."&#39;);\'>".$post->post_title."</a></li>";
							$searchTag[] = 	$post->post_title;
						}
						$josnTag = json_encode($searchTag);						
					  //======================= END TAG LIST======================	
					
			  ?>
              <?php 
			  	$createLabel ='<li><a href="javascript:void(0);" id="label_create_datatable">Create Label</a></li>';
				echo $createLabel;
			  ?>         
                      
            </ul>
          </div></div>
            <div class="span10">           
            <table id="mailboxDatatable" class="table table-bordered table-striped">
                <thead>
                	<tr>
                    <th>ID</th>
                    <th>To</th>
                    <th>From</th> 
                    <th>From Name</th>
                    <th>Subject</th>
                    <th>Message</th> 
                    <th>Tag</th>                   
                    <th>Attachments</th> 
                    <th>Label</th> 
                    <th>Received</th> 
                    <th>Attachment Name</th>
                    </tr>
                </thead>
                <tbody>
					<?php                    	
						
                        $table = $webapper->tables->emails;
						$emails = $wpdb->get_results("SELECT * FROM $table  WHERE user_id='$user_ID' ORDER BY received_on DESC");				
						foreach ( $emails as $email ) :
							echo stripslashes("<tr><td>$email->ID</td><td>$email->to</td><td>$email->from</td><td>$email->from_name</td><td id='$email->ID' class='linked-field'>$email->subject</td><td>"); echo stripslashes(htmlspecialchars_decode($email->message_body)); echo "</td>";	
							$checkTd= false;						
							foreach($customPostObjs as $post)
							{								
								if($post->post_title == $email->tag)
								{									
									echo stripslashes('<td>
									<a href="../singleview-shortcode/?postID='.$post->ID.'">'.$email->tag.'</a></td>');
									$checkTd = true;
								}								
							}
							if($checkTd ==false)
							{
								echo stripslashes('<td>'.$email->tag.'</td>');
							}
							if($email->attachment_path =='Y'):
								echo stripcslashes('<td style="text-align:center;"><input disabled type="checkbox" name="checkbox_'.$email->ID.'" id="checkbox_'.$email->ID.'" checked="checked"  /></td>');
							else: 
								echo "<td>&nbsp;</td>";
							endif;							
							echo stripcslashes("<td>$email->label</td><td>$email->received_on</td>");
							if($email->attachment_path =='Y'):
								$attTable = $webapper->tables->email_attachments;
								$allAtt="";
								$attchs = $wpdb->get_results("select * from $attTable where emails_id=$email->ID");
								foreach($attchs as $val)
								{
									$allAtt = $allAtt.$val->file_name." | ";
								}
								$allAtt = rtrim($allAtt, "| ");
								echo "<td>".$allAtt."</td>";
							else: 
								echo "<td>&nbsp;</td>";
							endif;
							echo "</tr>";
						endforeach;
                    ?>	
                </tbody>
            </table>            
            </div>
            </div>
                        
            <!-- Info Modal -->
            <div id="infoModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel" aria-hidden="true">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h3 id="infoModalLabel">Heads Up!</h3>
                </div>
                <div class="modal-body">
                    <div id="deleteWarning" style="display: block;">
                        <p><span class="label label-info">Info</span>&nbsp;Please select a row first. To do so, simply click on the row you would like to change.</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
                </div>
            </div>
            
            <!-- Compose Mail -->
            <form id="composeEmail"  action="" method="POST" enctype="multipart/form-data" onsubmit="return postForm('summernote');">
            <div id="composeModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel" aria-hidden="true">
                <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                 <h3 id="infoModalLabel">Compose Email</h3>                 
                </div>
                <div class="modal-body">
                    <div class="input-group">
                    <span class="input-group-addon">To:</span>                    
                   <!-- <input id="e21" class="span5" type="text" spellcheck="false" autocapitalize="off" autocorrect="off" autocomplete="off" />-->
                  
                <input style="margin-left: 0px; margin-bottom:10px;" id="txt_Recipient_email" type="text" name="recipients_email" class="span5" placeholder="Email" required="required">
               
                    
                    <!--<input id="xyzTest" type="text" name="recipients_email" style="width:456px;" placeholder="Recipients" >-->
                    </div>
                    <div class="input-group">
                    <span class="input-group-addon">Subject:</span>
                    <input type="text" name="subject_email" class="span5" placeholder="Subject" required="required">
                    </div>
                    	<div>
                        <textarea class="input-block-level" id="summernote" name="content" rows="18">
                        </textarea>
                        </div>
                    </div>                                       
                <div class="modal-footer">
                     	<div class="span3 btn-group">
                            <input type="submit" id="send_<?php echo $id; ?>_compose" name="sendButton" class="btn  btn-primary" value="Send" />
                            <input type="submit" id="save_<?php echo $id; ?>_compose" name="saveButton" class="btn  btn-primary" value="Save" />  
                            <input name="filesToUpload[]" id="filesToUpload" type="file" multiple="multiple" style="width: 185px" />   
                         </div>
                     	 <div class="span1">
                            	<input class="span1" type="text" data-provide="typeahead" name="composeTag" data-items="4" placeholder="Tag" autocomplete="off"  data-source='<?php echo $josnTag; ?>' />
                        </div>
                         <div class="span1">
                            <input class="span1" type="text" data-provide="typeahead" name="composeLabel" data-items="4" placeholder="Label" autocomplete="off"  data-source='<?php echo $jsonLabel; ?>' />
                        </div>
                        </div>
           	</div>
            </form>
            <!-- ADD LABEL -->
            <form name="frm_label" id="frm_label" method="post" action="">
            <div id="labelModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel" aria-hidden="true">
                <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                 <h3 id="infoModalLabel">Create Label</h3>
                </div>
                <div class="modal-body">
                	<div class="input-group">
                    <span class="input-group-addon">New Label:</span>
                    <input type="text" name="newLabel" class="span5" placeholder="New Label Name" required="required">
                    </div>
                </div>	
                <div class="divider"></div>
                <div class="modal-footer">                    
                <div class="btn-group">
                     <input type="button" data-dismiss="modal" aria-hidden="true" class="btn  btn-primary" value="Close" />
                     <input type="submit" id="saveLabel_<?php echo $id; ?>_datatable" name="save_lebel" class="btn  btn-primary" value="Save">
                     
                </div>
                </div>
            </div>
            </form>
            <form name="frm_tag" id="frm_tag" method="post" action="">
            <div id="tagModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel" aria-hidden="true">
                <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                 <h3 id="infoModalTag">Search Tag</h3>
                </div>               
                <div class="span6" style="padding:5px;">
                    <input class="span4" type="text" data-provide="typeahead" name="updateTag" data-items="4" placeholder="Tag" autocomplete="off"  data-source='<?php echo $josnTag; ?>' />
              		<input  type="hidden" name="recIds" id="recIds" />
                 </div>
                 <div class="modal-body"></div>                           
                <div class="modal-footer">                    
                <div class="btn-group">
                     <input type="button" data-dismiss="modal" aria-hidden="true" class="btn  btn-primary" value="Close" />
                     <input type="submit" id="saveTag" name="save_tag" class="btn  btn-primary" value="Save">
                </div>
            </div>
             </div>	
            </form>
             
			<!-- Edit Compose Form-->          
            <form name="frm_editMessage" id="frm_editMessage" action="" method="POST" enctype="multipart/form-data" onsubmit="return postForm('reply_text');" >            
            <div id="editMessageModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel" aria-hidden="true">
            	<div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>                
                <h3 id="infoModalSubLine">Reply Email</h3>             
                </div>
                <div class="modal-body">
                
                	<div class="input-group">
                    
                    <div id="editEmail" style="display:none;">
                    <div style="float:left;">To: &nbsp;</div>
                    <div class="input-group">
                    <input type="text" name="recipients_email" id="recipients_email_edit" class="span5 " placeholder="Recipients" required="required">
                     </div>
                    <div style="float:left; margin-top:60px; margin-left:0px;">Subject: &nbsp;</div>
                    <input style="margin-top:20px;" type="text" name="subject_email" id="email_subject_edit" class="span5" required="required">  
                    </div>
                    
                    <div id="viewEmail">
                    <div style="float:left;">From: &nbsp;</div>
                    <div name="recipients_email" id="recipients_email" style="float:left;"> </div>
                    <div id="receipt_time" style="text-align:right;"></div>
                    </div>
                    
                    </div>
                    
                    <div class="input-group">

                   <!-- <input type="text" name="subject_email" id="subject_email_edit" class="span5" placeholder="Subject" required="required">-->
                    </div>
                    	<div style="padding-top:20px;">
                        <!--<textarea class="input-block-level" id="summernote_editMessage" name="content" rows="18"></textarea>-->
                        <div id="summernote_editMessage" name="summernote_editMessage"> </div>
                        <div id="div_reply_text" style="display:none;"><textarea class="input-block-level" id="reply_text" name="content" rows="18"  ></textarea> </div>
                        </div>
                        <div id="messageBody_attachment">&nbsp;</div>
                </div>
                
                
                <div class="modal-footer" >
                	<div class="span3 btn-group" id="replyForwardButtons">                           
                     	<input type="button" name="reply"  id="reply" class="btn  btn-primary" value="Reply"/>
                        <input type="button" name="replyall" id="replyall" class="btn  btn-primary" value="Reply All" />
                        <input type="button" name="forward" id="forward" class="btn  btn-primary" value="Forward" />
                          <!--<input name="filesToUpload[]" id="filesToUpload2" type="file" multiple="multiple" style="width: 185px" />-->
                	</div>
                    
                     <div class="span3 btn-group" id="sendSaveButtons"  style="display:none;">
                            <input type="submit" id="send_<?php //echo $id; ?>_compose" name="sendButton" class="btn  btn-primary" value="Send" />
                            <input type="submit" id="save_<?php //echo $id; ?>_compose" name="saveButton" class="btn  btn-primary" value="Save" />  
                            <input name="filesToUpload[]" id="filesToUpload" type="file" multiple="multiple" style="width: 185px" />   
                         </div>
        
                    <div class="span1">
                        <input class="span1" type="text" data-provide="typeahead" name="composeTag" data-items="4" placeholder="Tag" autocomplete="off"  data-source='<?php echo $josnTag; ?>' />
                    </div>
                     <div class="span1">
                        <input class="span1" type="text" data-provide="typeahead" name="composeLabel" data-items="4" placeholder="Label" autocomplete="off"  data-source='<?php echo $jsonLabel; ?>' />
                    </div>
                   
                </div>
            </div>
            </form>  
                       
			<script type="text/javascript">
				// Store Commonly manipulated DOM nodes as objects
				nForm = jQuery('#<?php echo $id; ?>');
				nFormTask = jQuery('input[name="web_apper_task"]', nForm);
				nModal = jQuery('.modal', nForm);
				nModalHeader = jQuery('.modal-header h3', nModal)
				nModalBody = jQuery('.modal-body', nModal);
				nModalClose = jQuery('.modal-footer [data-dismiss="modal"]', nModal)
				//nModalSaveBtn = jQuery('.modal-footer #save', nModal)
				nModalElements = jQuery('.modal-body>*', nModal);
				nDeleteWarning = jQuery('#deleteWarning', nModal);
				nTable = jQuery('#mailboxDatatable');	
				var operation = "";
				var bodyHtml = "";
				var replyAndForwardEmail="";
				jQuery(document).ready(function($) {					
					$('#txt_Recipient_email').magicSuggest({						
						required:true,
						allowFreeEntries: false,
						width: 456,						
						data: <?php  echo $autoPopulateRecipient; ?>
					});					
					
								
					$('#summernote').summernote({
						  height: 200,   //set editable area's height
						  focus: true    //set focus editable area after Initialize summernote
						});					
					$('#reply_text').summernote({
						  height: 175,   //set editable area's height
						  focus: true    //set focus editable area after Initialize summernote
						});
					
					/*$('#summernote_editMessage').summernote({
						  height: 175,   //set editable area's height
						  focus: true    //set focus editable area after Initialize summernote
						});*/
					// Initialize dataTable					
					oTable = $(nTable).dataTable({
						<?php
							// Build the sDom parameter for dataTables
							global $template;
							if ( stristr($template, 'fullwidth') ) :
								$spanA = 7; $spanB = 7;
							else :
								$spanA = 4; $spanB = 5;
							endif;
							echo "'sDom': \" <'span18' <'#operationLabel'> <'span1' C><'span".$spanB."'fl>r>t<'row'<'span6'i><'span6'p>>\",\n";
						?>
						'sPaginationType': 'bootstrap',
						'aaSorting': [[ 9, 'desc']],
						'oLanguage': {
							'sLengthMenu': 'records per page <select>'+
							'<option value="10">10</option>'+
							'<option value="20">20</option>'+
							'<option value="30">30</option>'+
							'<option value="40">40</option>'+
							'<option value="50">50</option>'+
							'<option value="100">100</option>'+
							'</select>'
						},
						'aoColumnDefs': [ { 'bVisible': false, 'aTargets': [  0, 5, 7, 10 ] } ],
						'oColVis': {
							'buttonText': 'Columns',
							'bRestore': true,
							'sAlign': 'left',
							'sSize': 'css',
							'aiExclude': [ 0, 8, 4 , 10]
						},
					});
					$("#operationLabel").addClass("btn-group span4");
					$("#operationLabel").html("<button id='compose_<?php echo $id; ?>_datatable' class='btn  btn-primary'>Compose</button><button id='spam_<?php echo $id; ?>_datatable' class='btn  btn-primary'>Spam</button><button id='delete_<?php echo $id; ?>_datatable' class='btn  btn-primary'>Delete</button><button id='my_tag' class='btn  btn-primary'>Tag</button><button id='label_drodown_datatable' data-toggle='dropdown' class='btn dropdown-toggle btn  btn-primary'>Label<b class='caret'></b></button><ul class='dropdown-menu'><?php echo $labelList==""?"<li><a href='javascript:void(0);'>No label found.</a></li><li><a href='javascript:void(0);' id='label_create_no_datatable'>Create Label</a></li>":$labelList;?></ul>");
					
					// Add a click handler to the link cells
					oTable.on('hover', "tbody td.linked-field", function( e ) {
							if ( $(this).attr('id') ) {
									var contents = $(this).html();									
							contents = '<a href="javascript:void(0);" id="editMessage_'+$(this).attr('id')+'" class="editMessage_'+$(this).attr('id')+'">' + contents + '</a>';
									$(this).html(contents );
							}					
					});
					
					//Edit Modal Popup
					oTable.on('click', "tbody tr td.linked-field", function(e) {
							var temp = $(this).parent('tr')[0];
							var position = oTable.fnGetPosition(temp);
							var contents = oTable.fnGetData(position);
							jQuery("#viewEmail").show();
							jQuery("#editEmail").hide();
							jQuery("#summernote_editMessage").show();
							jQuery("#div_reply_text").hide();
							jQuery("#replyForwardButtons").show();
							jQuery("#sendSaveButtons").hide();
							$("#editMessageModal").modal();									
							$("#infoModalSubLine").html(contents[4]);
							operation =contents[4];
							var emails = contents[1];
							emails = emails.replace("<?php echo $user_email;?>","");
							var tempEmailArray = contents[2].split(",");
							var tempEmail="";
							var jsonTempEmail ="";
							var tempCount= tempEmailArray.length-1;
							for(var x=0; x<tempEmailArray.length; x++)
							{
								if(x==tempCount)
								{
									jsonTempEmail +="{\"id\":\""+tempEmailArray[x]+"\""+","+"\"name\":\""+tempEmailArray[x]+"\"}";
									tempEmail +="\""+tempEmailArray[x]+"\"";
								}
								else
								{
									jsonTempEmail +="{\"id\":\""+tempEmailArray[x]+"\""+","+"\"name\":\""+tempEmailArray[x]+"\"}"+",";
									tempEmail +="\""+tempEmailArray[x]+"\""+",";
								}
							}
							if(emails !='')
							{ 
								replyAndForwardEmail = 	tempEmail+","+"\""+emails+"\"";
								jsonTempEmail +=",{\"id\":\""+emails+"\""+","+"\"name\":\""+emails+"\"}";
							}
							else
							{
								replyAndForwardEmail = 	tempEmail;
							}
							$("#recipients_email_edit").val(contents[2]+","+emails);	
							$("#recipients_email").html(contents[2]);
							$("#reply_text").code(contents[5]);
							$("#summernote_editMessage").html(contents[5]);
							bodyHtml = contents[5];
							$("#receipt_time").html(contents[9]);							
							if(contents[10] !='&nbsp;')
							{
								$("#messageBody_attachment").html('<p></p><b>Attachments:</b><p></p>'+contents[10]);
							}	
							else
							{
								$("#messageBody_attachment").html('');
							}		
							var tempPredefEmail = <?php  echo $autoPopulateRecipient; ?>;
							tempPredefEmail.push($.parseJSON(jsonTempEmail));
							$('#recipients_email_edit').magicSuggest({						
								required:true,
								value: [$.parseJSON(replyAndForwardEmail)],
								allowFreeEntries: true,
								width: 456,
								data: tempPredefEmail
							});							
							return false;
						});

					// Add a click handler to the table rows - Sets selected row class
					oTable.on("click", "tr", function( e ) {
						if ( $('td', this).hasClass('dataTables_empty') )
						return;
						$(this).toggleClass('row_selected');	
						var selected = false;
						$('tr', oTable).each(function() {
						if ( $(this).hasClass('row_selected') ) {
							selected = true;
							}
						});
						if ( selected === true ) {
							$('#selectRowsDatatable').text('Deselect All');
						} else {
							$('#selectRowsDatatable').text('Select All');
						}
					});
			     
					$("#spam_<?php echo $id; ?>_datatable").on('click', function(){	
							var ids = "";
							var positionIs= Array();
							var operation = 'Spam';
						  $('tr.row_selected', oTable).each( function() {							  	
								var position = oTable.fnGetPosition(this);
								positionIs.push( position);
								var id = oTable.fnGetData(position)[0];	
								ids += id+",";														
								});	
								if(ids !="")
								{								  								
								  $.ajax({									
									url: "<?php echo site_url('wp-admin/admin-ajax.php'); ?>",
									type: "post",
									data: { action: 'web_apper<?php echo $this->shortcode; ?>', 'web_apper_nonce':'<?php echo wp_create_nonce( 'WebApperAwesomeness!87' ); ?>', ids: ids, status: operation },
									success: function(data) {								
										if(data=='success'){													
											$.each( positionIs, function(key, value ) {
													oTable.fnUpdate( operation, value, 8, false );
												});
												positionIs.clear();
												$('tr.row_selected',oTable).each( function() {						
													$('.row_selected').removeClass('row_selected');
												});
											}
										},
									error: function (xhr, ajaxOptions, thrownError) {
											alert(xhr.status+': '+thrownError);
										}
									});	
								}
								else
								{
									$("#infoModal").modal();
								}
						});
					$("#delete_<?php echo $id; ?>_datatable").on('click', function(){
																				 
							var ids = "";
							var positionIs= Array();
							var operation = 'Trash';
						  $('tr.row_selected', oTable).each( function() {							  	
								var position = oTable.fnGetPosition(this);
								positionIs.push( position);
								var id = oTable.fnGetData(position)[0];	
								ids += id+",";														
								});	
								if(ids !="")
								{
									if ( confirm( 'Are you sure you wish to delete these rows?' ))
									{								  								
									  $.ajax({									
										url: "<?php echo site_url('wp-admin/admin-ajax.php'); ?>",
										type: "post",
										data: { action: 'web_apper<?php echo $this->shortcode; ?>', 'web_apper_nonce':'<?php echo wp_create_nonce( 'WebApperAwesomeness!87' ); ?>',ids: ids, status: operation},
										success: function(data) {								
											if(data=='success'){													
												$.each( positionIs, function(key, value ) {	
														oTable.fnUpdate( operation, value, 8, false );															
														//oTable.fnDeleteRow(value);
													});														
													positionIs.clear();
													$('tr.row_selected',oTable).each( function() {						
													$('.row_selected').removeClass('row_selected');
													});
												}
											},
										error: function (xhr, ajaxOptions, thrownError) {
												alert(xhr.status+': '+thrownError);
											}
										});	
									}
								}
								else
								{
									$("#infoModal").modal();
								}
						});
					$("#compose_<?php echo $id; ?>_datatable").on('click', function(){
						$("#composeModal").modal();						
					});
					
					$('#composeModal').on('show', function () {
							$(this).find('.modal-body').css({width:'auto',
													   height:'auto', 
													  'max-height':'100%'});
						});
					//Soumen
					$("#label_create_datatable").on('click', function(){						
						$("#labelModal").modal();						
					});	
					
					$("#my_tag").on('click', function(){						
							
						var ids="";
						var positionIs= Array();
						 $('tr.row_selected', oTable).each( function() {							  	
							var position = oTable.fnGetPosition(this);
							positionIs.push( position);
							var id = oTable.fnGetData(position)[0];	
							ids += id+",";	
						});
						if(ids !="")
						{
							$("#recIds").val(ids);
							$("#tagModal").modal();
						}
						else
						{
							$("#infoModal").modal();
						}
					});	
					
					$("#label_create_no_datatable").on('click', function(){
						$("#labelModal").modal();						
					});						
				});
				
				Array.prototype.clear = function()
				{
					this.length = 0;
				};
				var postForm = function(id) {
						var content = jQuery('textarea[name="content"]').val(jQuery('#'+id+'').code());										
					}
				var prevId="inbox";	
				var changeOperationStatus = function(id, value)
				{
					jQuery('tr.row_selected',oTable).each( function() {						
						jQuery('.row_selected').removeClass('row_selected');
					});				
					jQuery("#search").val(value);
					jQuery(nTable).dataTable().fnFilter(value);
					if(jQuery("#"+prevId+"").hasClass('active'))
					{
						jQuery("#"+prevId+"").removeClass('active');
					}
					jQuery("#"+id+"").addClass('active');
					prevId = id;
				}
								
				var ChangeLabel = function(value)
				{					
					var ids = "";
					var positionIs= Array();
					var operation = value;
				  jQuery('tr.row_selected', oTable).each( function() {							  	
						var position = oTable.fnGetPosition(this);
						positionIs.push( position);
						var id = oTable.fnGetData(position)[0];	
						ids += id+",";														
						});	
						if(ids !="")
						{								  								
						  jQuery.ajax({									
							url: "<?php echo site_url('wp-admin/admin-ajax.php'); ?>",
							type: "post",
							data: { action: 'web_apper<?php echo $this->shortcode; ?>', 'web_apper_nonce':'<?php echo wp_create_nonce( 'WebApperAwesomeness!87' ); ?>', ids: ids, status: operation},
							success: function(data) {																
								if(data=='success'){													
									jQuery.each( positionIs, function(key, value ) {
											var prevVal = jQuery(nTable).dataTable().fnGetData(value)[8];
											var finalLabel = prevVal+","+operation;
											var finalLabelArray = finalLabel.split(",");
											var fVal = jQuery.unique(finalLabelArray);																					
											oTable.fnUpdate( fVal, value, 8, false );
										});
										positionIs.clear();
										jQuery('tr.row_selected',oTable).each( function() {						
											jQuery('.row_selected').removeClass('row_selected');
										});
									}
								},
							error: function (xhr, ajaxOptions, thrownError) {
									alert(xhr.status+': '+thrownError);
								}
							});	
						}
						else
						{
							jQuery("#infoModal").modal();
						}
				}
				
				
				var ChangeTag = function(value)
				{					
					var ids = "";
					var positionIs= Array();
					var operation = value;
				  jQuery('tr.row_selected', oTable).each( function() {							  	
						var position = oTable.fnGetPosition(this);
						positionIs.push( position);
						var id = oTable.fnGetData(position)[0];	
						ids += id+",";														
						});	
						if(ids !="")
						{								  								
						  jQuery.ajax({									
							url: "<?php echo site_url('wp-admin/admin-ajax.php'); ?>",
							type: "post",
							data: { action: 'web_apper<?php echo $this->shortcode; ?>', 'web_apper_nonce':'<?php echo wp_create_nonce( 'WebApperAwesomeness!87' ); ?>', ids: ids, status: operation, effectedColumn: 'Tag'},
							success: function(data) {												
								if(data=='success'){																						
									jQuery.each( positionIs, function(key, value ) {
											/*var prevVal = jQuery(nTable).dataTable().fnGetData(value)[6];
											var finalLabel = prevVal+","+operation;
											var finalLabelArray = finalLabel.split(",");
											var fVal = jQuery.unique(finalLabelArray);*/																					
											oTable.fnUpdate( operation, value, 6, false );
										});
										positionIs.clear();
										jQuery('tr.row_selected',oTable).each( function() {						
											jQuery('.row_selected').removeClass('row_selected');
										});
									}
								},
							error: function (xhr, ajaxOptions, thrownError) {
									alert(xhr.status+': '+thrownError);
								}
							});	
						}
						else
						{
							jQuery("#infoModal").modal();
						}
				}
				
				jQuery("#reply").on('click',function(){
					 jQuery("#reply_text").code("<br /><br /><br /><br />"+bodyHtml);
					 jQuery("#infoModalSubLine").html("Reply Email");											 
					 jQuery("#viewEmail").hide();
					 jQuery("#editEmail").show();
					 jQuery("#summernote_editMessage").hide();
					 jQuery("#div_reply_text").show();
					 jQuery("#replyForwardButtons").hide();
					 jQuery("#sendSaveButtons").show();					 
					 jQuery("#email_subject_edit").val("Re: "+operation);
					  return false;
					 });
				
				jQuery("#forward").on('click',function(){	
					 jQuery("#infoModalSubLine").html("Forward Email");	
					 jQuery("#reply_text").code("<br /><br /><br /><br />---------- Forwarded message ----------<br />"+bodyHtml);	 
					 jQuery("#viewEmail").hide();
					 jQuery("#editEmail").show();
					 jQuery("#summernote_editMessage").hide();
					 jQuery("#div_reply_text").show();
					 jQuery("#replyForwardButtons").hide();
					 jQuery("#sendSaveButtons").show();
					 jQuery("#email_subject_edit").val("Fwd: "+operation);
					  return false;
					 });
				jQuery("#replyall").on('click',function(){
					 jQuery("#reply_text").code("<br /><br /><br /><br />"+bodyHtml);
					 jQuery("#infoModalSubLine").html("Reply All Email");				 
					 jQuery("#viewEmail").hide();
					 jQuery("#editEmail").show();
					 jQuery("#summernote_editMessage").hide();
					 jQuery("#div_reply_text").show();
					 jQuery("#replyForwardButtons").hide();
					 jQuery("#sendSaveButtons").show();
					 jQuery("#email_subject_edit").val("Re: "+operation);
					  return false;
					 });	
					 			
			</script>
            <?php
	}


    /**
     * Handles ajax requests
     *
     * @since 1.0
     */
	public function sendAjaxResponse() {
		if(isset($_POST['effectedColumn']))
		{
			if($_POST['effectedColumn'] == "Tag")
			{
				echo $this->change_email_tag($_POST['status'], $_POST['ids']);
			}
		}		
		else if ( isset( $_POST['status'] ) ) :
			check_ajax_referer( 'WebApperAwesomeness!87', 'web_apper_nonce' );  // Verify the security nonce
			if ( $_POST['status'] == 'Trash' || $_POST['status']=='Spam' ) :
					echo $this->delete_spam_record($_POST['status'], $_POST['ids']);					
					die();  // Prevents ajax from returning a '0'
			else:
				echo $this->change_email_label($_POST['status'], $_POST['ids']);
			endif;
			die();  // Prevents ajax from returning a '0'
		endif;
		die();
	}


    /**
     * Delete OR Spam a record
     *
     * @since 1.0
     */
	public function delete_spam_record($status, $operationIds) {
		global $webapper, $wpdb;                            
		$table = $wpdb->prefix . 'web_apper_emails';
		$ids = $operationIds;
		$ids = rtrim($ids,",");
		$idArray = explode(",",$ids);
		foreach($idArray as $id)
		{
			$query = $wpdb->prepare("UPDATE $table SET label = %s WHERE ID = %d", $status, $id );
			$wpdb->query( $query );
		}		
		return 'success';
	}
	/**
     * Label a record
     *
     * @since 1.0
     */
	 public function change_email_label($status, $operationIds) {
		global $webapper, $wpdb;                            
		$table = $wpdb->prefix . 'web_apper_emails';
		$labelVal= array();
		$ids = $operationIds;
		$ids = rtrim($ids,",");
		$idArray = explode(",",$ids);
		foreach($idArray as $id)
		{
			$labelValue = $wpdb->get_row("SELECT * FROM $table  WHERE ID=$id");
			$results = explode(",",$labelValue->label);
			foreach($results as $result)
			{
				if(!in_array(trim($result),$labelVal))
					$labelVal[] = trim($result);
			}
			if(!in_array($status,$labelVal))		
				$labelVal[] = trim($status);
			$query = $wpdb->prepare("UPDATE $table SET label = %s WHERE ID = %d", implode(",", $labelVal), $id );
			$wpdb->query( $query );
		}
		return 'success';
	}
	 public function change_email_tag($status, $operationIds) {
		global $webapper, $wpdb;                            
		$table = $wpdb->prefix . 'web_apper_emails';
		$ids = $operationIds;
		$ids = rtrim($ids,",");
		$idArray = explode(",", $ids);		
		foreach($idArray as $id)
		{
			$query = $wpdb->prepare("UPDATE $table SET tag = %s WHERE ID = %d", $status, $id );
			$wpdb->query( $query );			
		}
		return 'success';
 	}
			
}
$initialize = new MailBox(); 

?>